/**
 * 
 */
package com.autonavi.car.si.FileStore.util;

import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.autonavi.car.si.FileStore.Config.FTPHostManager.FTPHost;
import com.autonavi.car.si.FileStore.model.FileVO;

/**
 * @author kucheng.liao@autonavi.com
 * @date Nov 24, 2014
 * 
 */
public class FtpUtil {

	private static Logger log = LoggerFactory.getLogger(FtpUtil.class);

	/**
	 * 获取ftp连接
	 * 
	 * @param host
	 * @return
	 * @throws IOException
	 */
	private static FTPClient getClient(FTPHost host) throws IOException {
		FTPClient client = new FTPClient();
		client.setDefaultTimeout(host.getTimeout());
		client.setControlEncoding("UTF-8");
		client.connect(host.getHostName(), host.getPort());
		client.login(host.getUser(), host.getPwd());
		client.setFileType(FTPClient.ASCII_FILE_TYPE);
		client.enterLocalPassiveMode();
		int replyCode = client.getReplyCode();
		if ((!FTPReply.isPositiveCompletion(replyCode))) {
			log.error("connection to ftp server Exception host :" + host.getHostName() + " port : " + host.getPort());
			throw new IOException("建立FTP socket连接异常");
		}
		return client;
	}

	/**
	 * 关闭socket连接
	 * 
	 * @param client
	 */
	private static void closeClent(FTPClient client) {
		if (null != client) {
			try {
				client.logout();
			} catch (IOException e) {
				log.error("", e);
			}
			try {
				client.disconnect();
			} catch (IOException e) {
				log.error("", e);
			}
		}
	}

	/**
	 * 上传
	 * 
	 * @param host
	 * @param name
	 * @param in
	 * @return
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public static int upload(FTPHost host, FileVO vo) throws IOException {
		if (log.isDebugEnabled()) {
			log.debug(" upload data , host " + host);
			log.debug(" upload data , fileStorePaht =" + vo.getStorePath() + ",  filename=" + vo.getUniqueFileName());
		}
		FTPClient client = null;
		try {
			client = getClient(host);

			client.changeWorkingDirectory(host.getRootPath());

			// 切换到存放文件的目录路径
			if (!client.changeWorkingDirectory(vo.getDate())) {
				client.makeDirectory(vo.getDate());
				client.changeWorkingDirectory(vo.getDate());
			}

			if (!client.changeWorkingDirectory(vo.getSlice() + "")) {
				client.makeDirectory(vo.getSlice() + "");
				client.changeWorkingDirectory(vo.getSlice() + "");
			}

			client.makeDirectory(vo.getStorePath());
			if (client.storeFile(vo.getUniqueFileName(), vo.getIn())) {
				return 200;
			} else {
				return 500;
			}
		} finally {
			closeClent(client);
		}
	}

	/**
	 * 下载文件
	 * 
	 * @param host
	 *            主机信息
	 * @param name
	 *            文件名称
	 * @param out
	 *            输出流
	 * @return
	 * @throws IOException
	 */
	public static void download(FTPHost host, FileVO vo) throws IOException {
		FTPClient client = null;
		try {
			client = getClient(host);

			if (client.changeWorkingDirectory(host.getRootPath()) && client.changeWorkingDirectory(vo.getStorePath())) {
				vo.setIn(client.retrieveFileStream(vo.getUniqueFileName()));
			}
			if (log.isDebugEnabled()) {
				log.debug("下载文件 " + host.getRootPath() + "/" + vo.getStorePath() + "/" + vo.getUniqueFileName());
			    log.debug("host:"+host);
			}
		} finally {
			closeClent(client);
		}
	}
}
